# Maintainer: George Rawlinson <george@rawlinson.net.nz>

pkgname=cloudflared
pkgver=2023.10.0
pkgrel=1
pkgdesc='Command-line client for Cloudflare Tunnel'
arch=('loong64' 'x86_64')
url='https://github.com/cloudflare/cloudflared'
license=('Apache')
depends=('glibc')
makedepends=('git' 'go')
options=('!lto')
_commit='c1d8c5e960ed07eab208f98ec02a011f443f1f5f'
source=("$pkgname::git+$url.git#commit=$_commit")
b2sums=('SKIP')

pkgver() {
  cd "$pkgname"

  git describe --tags
}

prepare() {
  cd "$pkgname"

  # create directory for build output
  mkdir build
}

build() {
  cd "$pkgname"

  # define buildtime for use in man page & binary
  local build_time="$(date -d@"$SOURCE_DATE_EPOCH" +%Y%m%d-%H:%M:%S)"

  # generate man page
  sed -e "s/\${VERSION}/${pkgver}/" \
      -e "s/\${DATE}/${build_time}/" \
    cloudflared_man_template > "build/$pkgname.1"

  # verify go modules
  go mod verify

  # set Go flags
  export CGO_CPPFLAGS="${CPPFLAGS}"
  export CGO_CFLAGS="${CFLAGS}"
  export CGO_CXXFLAGS="${CXXFLAGS}"
  export GOPATH="${srcdir}"

  # build cloudflared
  go build -v \
    -buildmode=pie \
    -mod=readonly \
    -modcacherw \
    -ldflags "-compressdwarf=false \
    -linkmode external \
    -extldflags ${LDFLAGS} \
      -X main.Version=${pkgver} \
      -X main.BuildTime=${build_time} \
      -X github.com/cloudflare/cloudflared/cmd/cloudflared/updater.BuiltForPackageManager=pacman" \
    -o build \
    ./cmd/...
}

# TODO look at me, tests hang!
#check() {
#  cd "$pkgname"
#
#  go test -v -mod=vendor -race ./...
#}

package() {
  cd "$pkgname"

  # binary
  install -vDm755 -t "$pkgdir/usr/bin" "build/$pkgname"

  # man page
  install -vDm644 -t "$pkgdir/usr/share/man/man1" "build/$pkgname.1"
}

# vim:set ts=2 sw=2 et:
